<template>
  <a-cascader
    v-model="selectValue"
    :options="treeData"
    :fieldNames="{
      label: 'name',
      value: 'id',
      children: 'children'
    }"
    :placeholder="placeholder"
    change-on-select
    @change="handChange"
  />
</template>

<script>
import { getWarehouseGroup } from '@/api/content/warehouse';
import { cloneDeep } from 'lodash-es';

export default {
  props: {
    activeTabKey: {
      type: String,
      required: true,
      default: ''
    },
    // 提示语
    placeholder: {
      type: String,
      default: '请选择上级分组,不选择则为一级分组'
    },

    // 是否显示未分组
    undistributed: {
      type: Boolean,
      default: false
    },
    // 最多选择级别
    maxLevel: {
      type: Number,
      default: 4
    },
    // 绑定值-分组ID
    value: {
      type: Number | String
    }
  },
  data() {
    return {
      oldData: [], // 初始数据
      treeData: [],
      selectValue: []
    }
  },
  watch: {
    value: {
      handler(val) {
        this.toggleSelectValue(val);
      },
      deep: true
    }
  },
  created() {
    this.getWarehouseGroupList()
  },
  methods: {
    async getWarehouseGroupList() {
      const that = this;
      const { data } = await getWarehouseGroup(that.activeTabKey)
      that.oldData = cloneDeep(data);
      that.treeData = that.handleTree(data, 0)
      if (that.undistributed) {
        const ungrouped = data.find(v => v.id === -1) // 未分组
        ungrouped && that.treeData.unshift(ungrouped)
      }

      // 分组回显
      this.toggleSelectValue(that.value);
    },
    handleTree(treeData, parentId) {
      let treeArr = []
      for (let i = 0; i < treeData.length; i++) {
        let item = treeData[i]
        if (item.parentId === parentId) {
          const _children = this.handleTree(treeData, item.id)
          _children.length && item.level < this.maxLevel ? (item.children = _children) : delete item.children
          treeArr.push(item);
        }
      }
      return treeArr
    },
    toggleSelectValue(groupId) {
      const findItem = this.oldData.find(v=> v.id === groupId);
      if(findItem && findItem.parentStrIds){
        const list = findItem.parentStrIds.split(',');
        let selectKeys = [];
        list.forEach(v => {
          if(v){
            selectKeys.push(Number(v))
          }
        });
        this.selectValue = selectKeys;
      }else if(findItem && findItem.id === -1){
        this.selectValue = [-1]
      }else{
        this.selectValue = []
      }
    },
    handChange(value) {
      this.$emit('input', value.length ? value[value.length -1] : undefined);
      this.$emit('change')
    }
  }
}
</script>

<style lang="less" scoped></style>
